package auth_https

import (
	"crypto/tls"
	"crypto/x509"
	"log"
	"net/http"
)

type CertClient struct {
	CaCipher   string // 必填  CaCipher 暗号(相当于密码的意思)
	CaZipPath  string // 必填
	ClientCert string //单端加密不需要填写
	ClientKey  string //单端加密不需要填写
}

// HttpsClient 只需要一个 ca 证书
func (cc *CertClient) HttpsClient() *http.Client {

	//caCrt, err := os.ReadFile(cc.CaZipPath)
	caCrt, _, err := OpenZip(cc.CaZipPath, cc.CaCipher)
	if err != nil {
		log.Fatal("read ca.crt file error:", err.Error())
	}

	pool := x509.NewCertPool()
	pool.AppendCertsFromPEM(caCrt)

	tr := &http.Transport{
		TLSClientConfig: &tls.Config{
			//客户端设置RootCAs，客户端 验证服务端证书。
			RootCAs: pool,
		},
	}

	return &http.Client{Transport: tr}
}

// HttpsClientDoubleCert 双端证书验证
func (cc *CertClient) HttpsClientDoubleCert() *http.Client {

	caCrt, _, err := OpenZip(cc.CaZipPath, cc.CaCipher)
	if err != nil {
		log.Fatal("read ca.crt file error:", err.Error())
	}

	pool := x509.NewCertPool()
	pool.AppendCertsFromPEM(caCrt)

	cliCrt, err := tls.LoadX509KeyPair(cc.ClientCert, cc.ClientKey)
	if err != nil {
		log.Fatalln("LoadX509KeyPair error:", err.Error())
	}

	tr := &http.Transport{
		TLSClientConfig: &tls.Config{
			//设置错误或者设置反了都会造成认证不通过。
			//客户端设置RootCAs，用户客户端验证服务端证书。
			RootCAs:      pool,
			Certificates: []tls.Certificate{cliCrt},
		},
	}
	return &http.Client{Transport: tr}
}
